package com.liull.netty.nio.net.nonblock;

import cn.hutool.core.lang.Console;
import com.liull.netty.nio.bytebuffer.ByteBufferUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: liull
 * @Description:
 * @Date: Created in 22:19 2021/7/22
 * @Modified By:
 */
public class NonBlockServer {
    public static void main(String[] args) {
        // 使用NIO来理解阻塞模式
        // 1.创建了服务器
        try (ServerSocketChannel ssc = ServerSocketChannel.open()) {
            // ServerSocketChannel切换为非阻塞
            ssc.configureBlocking(false);
            // 2。绑定监听端口
            ssc.bind(new InetSocketAddress(4567));
            // 3.连接集合
            List<SocketChannel> channels = new ArrayList<>();
            ByteBuffer buffer = ByteBuffer.allocate(16);
            while (true) {
                Thread.sleep(200);
                // Console.log("connecting...");
                // 非阻塞模式下 没有接收到客户端连接 返回null
                final SocketChannel channel = ssc.accept();
                if (channel != null) {
                    Console.log("connected...channel:{}", channel);
                    channel.configureBlocking(false);
                    channels.add(channel);
                }
                for (SocketChannel ch : channels) {
                    // Console.log("before read ... {}", channel);
                    // 非阻塞方法 没有读到数据返回0 读到结束返回-1
                    final int read = ch.read(buffer);
                    if (read > 0) {
                        buffer.flip();
                        ByteBufferUtil.printDesc(buffer);
                        buffer.clear();
                    }

                }
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
